<template>
  <div>
    <el-form :model="params" label-position="right" size="small" label-width="110px" class="base-search-more">
      <el-row>
        <el-col :span="6" v-if="$store.state.showAgent">
          <el-form-item label="所属区域">
            <el-select style="width:100%" v-model="form.agentid" filterable default-first-option
              placeholder="--区域--" @change="$refs.pagination.handleSizeChange(10)">
              <el-option v-for="item in restaurants" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="荣誉等级">
            <el-select style="width:100%;" v-model="params.sort" :clearable="true">
              <el-option v-for="item in sortList" :key="item.sortname" :label="item.sortname" :value="item.sort" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="$store.state.showAgent?12:18" style="text-align: right">
          <el-form-item label-width="0">
            <el-button type="primary" icon="el-icon-search" @click="$refs.pagination.handleSizeChange(10)">查询</el-button>
            <el-button type="primary" plain @click="addPlayer(1)">添加</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="base-table-wrap">
      <el-table :data="tableData.creditlevel" stripe style="width: 100%">
        <el-table-column prop="sortname" label="荣誉等级" min-width="100" align="center" />
        <!-- <el-table-column prop="startgrade" label="开始荣誉分数" min-width="100" align="center" />
        <el-table-column prop="endgrade" label="结束荣誉分数" min-width="100" align="center" /> -->
        <el-table-column label="基础距离" min-width="100" align="center">
          <template slot-scope="scope">{{filtersKmToOtherUnit(scope.row.distan)}}{{comConfig.lengthUnit}}</template>
        </el-table-column>
        <el-table-column label="距离超出提成" min-width="100" align="center">
          <template slot-scope="scope">{{scope.row.price}}{{comConfig.unit}}/{{filtersKmToOtherUnit(1)}}{{comConfig.lengthUnit}}</template>
        </el-table-column>
        <el-table-column label="最大提成" min-width="100" align="center">
          <template slot-scope="scope">{{scope.row.maxprice}}{{comConfig.unit}}</template>
        </el-table-column>
        <el-table-column prop="createtime" label="添加时间" min-width="120" align="center" />
        <el-table-column fixed="right" label="操作" width="100">
          <template slot-scope="scope">
            <el-button class="el-text-check" type="text" size="mini" @click="addPlayer(2,scope.row)">修改</el-button>
            <el-button class="el-text-danger" type="text" size="mini" @click="remove(scope.$index,tableData.creditlevel)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pt-table-loading v-show="isloadingTable" />
      <pt-pagination ref="pagination" :total="tableData.count" @listeningEvent="triggerEvent" />
    </div>
    <el-dialog :title="(edit ? '修改': '新增')+ '骑手等级'" v-dialogDrag :visible.sync="dialogTableVisible"  width="700px" >
      <el-form :model="form" ref="ruleForm" label-width="130px" size="small">
       <el-form-item label="所属区域" prop="agentid" :rules="[{ required: true, message: '请在列表页面上选择区域', trigger: 'change' }]">
          <el-row type="flex">
            <el-select v-model="form.agentid" :disabled="true">
              <el-option v-for="item in restaurants" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
            <el-tooltip class="item" effect="dark" content="此处和列表页面同步,若想更改请在列表页面更改" placement="top-start">
              <el-button type="text" icon="el-icon-question" />
            </el-tooltip>
          </el-row>
        </el-form-item>
        <el-form-item label="荣誉等级" prop="sort" :rules="[{ required: true, message: '请选择荣誉等级' }]">
          <el-select v-model="form.sort">
            <el-option v-for="item in sortList" :key="item.sortname" :label="item.sortname" :value="item.sort" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="荣誉等级分数" required style="margin-bottom: 0">
          <el-row type="flex">
            <el-form-item prop="startgrade" :rules="[{ required: true, message: '请输入开始分数', trigger: 'blur'}]">
              <el-input-number class="no-add-less" style="width: 100px" v-model="form.startgrade" :min='0' :max='form.endgrade ? form.endgrade : 9999' :precision='0' />
            </el-form-item>
            <span style="margin: 0 5px;">-</span>
            <el-form-item prop="endgrade" :rules="[{ required: true, message: '请输入结束分数'} ]">
              <el-input-number class="no-add-less" style="width: 100px" v-model="form.endgrade" :min='form.startgrade ? form.startgrade: 0' :max='9999' :precision='0' />
            </el-form-item>
          </el-row>
        </el-form-item> -->
         <el-form-item label="基础配送提成" prop="commission" :rules="[{ required: true, message: '请输入基础配送提成'}]">
          <el-input-number class="no-add-less" style="width: 100px" v-model="form.commission" :min='0' :max='9999' :precision='2' />
          <span style="margin: 0 5px">{{comConfig.unit}}</span>
        </el-form-item>
        <el-form-item label="基础配送距离" required style="margin-bottom: 0">
          <el-row type="flex">
            <el-form-item prop="distan" :rules="[{ required: true, message: '请输入基础配送距离'}]">
              <el-input-number class="no-add-less" style="width: 100px" v-model="form.distan" :min='0' :max='9999' :precision='1' />
              <span style="margin: 0 5px">{{comConfig.lengthUnit}}，超出部分每{{filtersKmToOtherUnit(1)}}{{comConfig.lengthUnit}}</span>
            </el-form-item>
            <el-form-item prop="price" :rules="[{ required: true, message: '请输入金额'}]">
              <el-input-number class="no-add-less" style="width: 100px" v-model="form.price" :min='0' :max='9999' :precision='2' />
              {{comConfig.unit}}提成
            </el-form-item>
          </el-row>
        </el-form-item>
        <el-form-item label="特殊时段附加提成" style="margin-bottom: 0;">
          <el-row type="flex">
            <el-row>
              <el-row type="flex" v-for="(item,index) in form.timeextracts" :key="index">
                <el-form-item :prop="'timeextracts.' + index + '.startdate'" :rules="[{ required: true, message: '请选择时间段'}]"
                  style="width: 100px; margin-bottom:18px">
                  <el-time-select style="width: 100%" placeholder="起始" v-model="item.startdate" :editable="false" :clearable="false"
                    :picker-options="{start: '00:00',step: '00:30',end: '24:00'}" />
                </el-form-item>
                <span style="line-height: 32px;margin: 0 5px;">-</span>
                <el-form-item :prop="'timeextracts.' + index + '.enddate'" :rules="[{ required: true, message: '请选择时间段'}]"
                  style="width: 100px; margin-bottom:18px">
                  <el-time-select style="width: 100%" placeholder="结束" v-model="item.enddate" :editable="false" :clearable="false"
                    :picker-options="{start: '00:00',step: '00:30',end: '24:00',minTime: item.startdate}" />
                </el-form-item>
                <span style="margin: 0 5px;">内</span>
                <el-form-item :prop="'timeextracts.' + index + '.commission'" :rules="[{ required: true, message: '请输入金额'}]">
                  <el-input-number class="no-add-less" style="width: 100px" v-model="item.commission" :min='0' :max='9999' :precision='2' />
                  <span style="margin-left: 5px">{{comConfig.unit}}</span>
                </el-form-item>
                  <div class="flex-row-ver butnsdel" @click="delDistanceCharge()"><i class="el-icon-remove"></i></div>
              </el-row>
            </el-row>
            <div v-if='form.timeextracts.length< 4' class="butns">
            <el-button type='primary' style='padding: 6px 4px' size='mini' :disabled='isshow'
              icon='el-icon-circle-plus-outline' @click="addDistanceCharge()">
              ({{form.timeextracts.length}}/4)
            </el-button>
          </div>
          </el-row>
        </el-form-item>
        <el-form-item label="每单最高提成" prop="maxprice" :rules="[{ required: true, message: '请输入金额'}]">
          <el-input-number class="no-add-less" style="width: 100px;" v-model="form.maxprice" :min='minPrice' :max='9999' :precision='2' />
          <span style="margin-left: 5px">{{comConfig.unit}}</span>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="isloadingSave" @click="submitForm('ruleForm')">提交信息</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
  import { kmToOtherUnit, otherUnitToKm } from '@/utils/unitChange.js'
  export default {
    data() {
      return {
        isloadingSave: false,  //保存或修改
        isloadingTable: false, //表单等待
        dialogTableVisible: false,
        edit: '', // 编辑的id
        sortList: [
          { sortname: '青铜', sort: 1 },
          { sortname: '白银', sort: 2 },
          { sortname: '黄金', sort: 3 },
          { sortname: '铂金', sort: 4 },
          { sortname: '钻石', sort: 5 }
        ],
        form: {  //新增或修改角色
          agentid: '',
          endgrade: undefined, // 结束分数 ,无用数据
          startgrade: undefined, // 开始分数 ,无用数据
          sortname: undefined, // 等级名称
          sort: null,
          commission: undefined, // 基础配送费
          commissionday: '1', // 无用数据
          commissionnight: '3', // 无用数据
          distan: undefined, // 配送距离
          price: undefined, // 每公里配送费
          maxprice: undefined, // 最高配送费
          timeextracts : [] // 新增的时间段
        },
        isshow: false, // 编辑按钮控制
        params: { //表格查询
          page: 0,
          pagesize: 10,
          sort: ''
        },
        tableData: {}   //表单数据
      }
    },
    computed: {
      minPrice() { // 最大配送费用的最小值
        const arr = this.form.timeextracts
        const numInArr = []
        if (arr.length) {
          arr.forEach(item => {
            numInArr.push(item.commission || 0)
          })
          return Math.max.apply(null,numInArr)
        } else {
          return 0
        }
      },
      restaurants() { // 区域数据
        return this.$store.state.agentList
      }
    },
    watch: { // 监听时间变化
      restaurants: {
        handler(val, oldVal) {
          if (val && val.length) {
            this.form.agentid = val[0].id
            this.getTableList()
          }
        },
        deep: true
      },
      'form.timeextracts': {
        handler(newValue, oldValue) {
          this.isshow = this.isShowEbutton(newValue)
        },
        deep: true
      }
    },
    methods: {
      filtersKmToOtherUnit(num) { // 单位换算
        return kmToOtherUnit(num)
      },
      isShowEbutton(arr) {
        let isShow = false
        if (arr.length) {
          for (let i = 0; i < arr.length; i++) {
            if (arr[i].startdate === '' || arr[i].enddate === '' || arr[i].commission === '') {
              isShow = true
            }
          }
        }
        return isShow
      },
      addDistanceCharge() { // 添加配送时间段
        this.form.timeextracts.push({startdate: '', enddate: '', commission: '' })
      },
      delDistanceCharge() { // 删除时间段
        this.form.timeextracts.pop()
      },
      timeNight(rule, value, callback) {         //时间验证
        if (this.form.timeday && value && value[0] <= this.form.timeday[1]) {
          callback(new Error('晚班开始时间应大于白班结束时间!'))
        } else {
          callback()
        }
      },
      addPlayer(type, row) { // 打开对话框，开始新增
        this.dialogTableVisible = true
        if (type == 1) {
          this.$nextTick(() => {
            this.$refs.ruleForm.resetFields()
            this.edit = ''
            this.form.endgrade = undefined
            this.form.startgrade = undefined
            this.form.sortname = ''
            this.form.sort = null
            this.form.commission = undefined
            this.form.commissionday = '1'
            this.form.commissionnight = '3'
            this.form.distan = undefined
            this.form.price = undefined
            this.form.maxprice = undefined
            this.form.timeextracts =  []
          })
        } else if (type == 2) {
          this.$nextTick(() => {
            this.$refs.ruleForm.resetFields()
            this.edit = row.id
            for(const key in this.form) {
              if (key !== 'timeextracts') {
                if (key === 'distan') {
                  this.form.distan = kmToOtherUnit(row.distan) || undefined
                  console.log(this.params.distan)
                } else {
                  this.form[key] = row[key] ? row[key]: ''
                }
              }
            }
            this.getLvupList(row.id, (res) => {
              this.isloadingTable = false
              if (res.success) {
                this.dialogTableVisible = true
                if (res.data && res.data.length) {
                  this.form.timeextracts = res.data.map(item => {
                    return {
                      startdate: item.starttime ? item.starttime.slice(11,16) : '',
                      enddate: item.endtime ? (item.endtime.slice(11,19) === '23:59:59' ? '24:00' : item.endtime.slice(11,16)): '',
                      commission: item.commission,
                      creditlevelId: item.creditlevelId,
                      id: item.id
                    }
                  })
                }
              }
            })
          })
        }
      },
      triggerEvent(type,val) { // 分页器
        if (type === 'page') {
          this.params.page = val - 1
        } else if (type === 'size') {
          this.params.page = 0
          this.params.pagesize = val
        }
        this.getTableList()
      },
      getTableList() { //获取骑手等级数据
        this.isloadingTable = true
       const params = { ...this.params }
        params.agentIds = this.form.agentid
        this.$http.get('/server/shopper/findcreditlevel?' + this.qs.stringify(params)).then(res => {
          if (res.data.success) {
            this.tableData = res.data
          }
        }).finally(() => { this.isloadingTable = false })
      },
      getLvupList(id,callback) { // 获取时间段
        this.isloadingTable = true
        this.$http.get(' /server/shopper//timeextracts?creditlevelId=' + id).then(res => {
          callback(res.data)
        }).catch(err => {
          this.isloadingTable = false
        })
      },
      submitForm(formName) { //提交修改
        this.$refs[formName].validate((valid) => {
          if (valid) {
            const params = { ...this.form }
            params.distan = otherUnitToKm(params.distan)
            if (params.timeextracts && params.timeextracts.length > 0 ) {
              params.timeextracts = params.timeextracts.map(item => {
                const startdate = `1970-02-01 ${item.startdate}:00`
                const enddate = item.enddate ? (item.enddate === '24:00' ?`1970-02-01 23:59:59` : `1970-02-01 ${item.enddate}:00`) : ''
                const startdates = (new Date(startdate)).getTime()
                const enddates = (new Date(enddate)).getTime()
                const obj = { startdate: startdates, enddate: enddates, commission: item.commission, timeAll: [startdate,enddate]}
                if (item.id) obj.id = item.id
                if (item.creditlevelId) obj.creditlevelId = item.creditlevelId
                  return obj
              })
            }
            params.sortname = this.sortList[params.sort - 1].sortname
            if (this.edit) {
              params.id = this.edit
              this.$http.post('/server/shopper/updatecreditlevel', JSON.stringify(params)).then(res => {
                if (res.data.success) {
                  this.$message.success('修改成功！')
                  this.dialogTableVisible = false
                  this.$refs.pagination.handleSizeChange(10)
                }
              })
            } else {
              this.$http.post('/server/shopper/addcreditlevel', JSON.stringify(params)).then(res => {
                if (res.data.success) {
                  this.$message.success('创建成功！')
                  this.dialogTableVisible = false
                  this.$refs.pagination.handleSizeChange(10)
                }
              })
            }
          }
        })
      },
      remove(index, rows) { // 删除骑手奥做
        let rem = { id: rows[index].id }
        this.$http.post('/server/shopper/delcreditlevel', JSON.stringify(rem)).then(res => {
          if (res.data.success) {
            this.$message.success('删除成功！')
            this.$refs.pagination.handleSizeChange(10)
          }
        })
      }
    },
    mounted() {
      if (this.restaurants && this.restaurants.length) {
        this.form.agentid = this.restaurants[0].id
        this.getTableList()
      }
    }
  }
</script>
<style lang="scss" scoped>
  .butnsdel {
    cursor: pointer;
    text-align: center;
    margin-left: 20px;
    padding: 0 5px;
    height: 32px;
    line-height: 32px;
    i {
     font-size: 25px;
     color: #f56c6c;
    }
  }
  .butns{
    margin-left: 15px;
  }
</style>
